<template>
	<div class="search">
		<!-- 顶部 -->
		<van-nav-bar
		  title="搜索"
		  left-arrow
		  fixed
		  z-index=100
		  @click-left="$router.go(-1)"
		/>
		
		<!-- 搜索框 -->
		<van-search v-model="value" placeholder="请输入搜索关键词" @search="search" class="sousuo"/>
		<div v-if="arr.length">
			搜索内容
		</div>
		<div v-else>
			<van-divider class="jilu"
			  :style="{ color: '#a0a1a2', borderColor: '#dededc', padding: '0 16px' }"
			  v-if="historyList.length"
			>
			  历史记录
			  <div class="clear_jilu">
				  <van-icon name="delete-o" @click="removeAll"/>
			  </div>
			</van-divider>
			<div style="padding: 0 10px;">
				<van-tag @click="history_sousuo(item)" @close="close(item)" color="#d5d6da" text-color="#757974" v-for="item,index in historyList" :key="index" closeable size="medium" type="primary" style="margin: 0 5px;">
				  {{item | text_clear}}
				</van-tag>
			</div>
			<van-divider
			  :style="{ color: '#a0a1a2', borderColor: '#dededc', padding: '0 16px' }"
			>
			  热门搜索
			</van-divider>
		</div>
	</div>
</template>

<script>
	import {home} from '@/api'
	import {getStorage,setStorage,removeStorage} from '@/plugins/localStorage'
	import { Dialog } from 'vant';//清空历史记录弹框
	export default {
	  name:'search',
	  data() {
	      return {
	        value: '',
			historyList:[],
			arr:[]
	      }
	  },
	  created(){
	  		  this.localHis()
	  },
	  methods: {
		  //历史记录搜索
		  history_sousuo(item){
			  this.value = item
			  this.request()
		  },
	   //获取历史记录，并给到数组中，让数组在里边循环使用
	   localHis(){
		   let res = getStorage('history')
		   if(!res)return
		   this.historyList = res
	   },
	   search(){
		   let res = getStorage('history')
		   let val = this.value.trim()
		   if(!val)return
		   //没有历史记录
		   if(!res){
			   setStorage('history',[val])
		   }else{
			   //如果res中没有val此数据则添入数组中
			   if(!res.includes(val)){
				   res.unshift(val)
				   setStorage('history',res)
			   }
		   }
		   this.localHis()
		   // this.value = ''
		   this.request()
	   },
	   //请求ajax进行页面跳转
	   async request(){
		   let res = await home()
		   this.arr = res.data.data.list
	   },
	   close(v){
		   removeStorage('history',v)
		   this.localHis()
	   },
	   removeAll(){
		   Dialog.confirm({
		     title: '温馨提示',
		     message: '你确定要删除？？？？？',
		   })
		     .then(() => {
		       // on confirm
			   window.localStorage.removeItem('history')
			   this.historyList = []
		     })
		     .catch(() => {
		       // on cancel
		     });
	   }
	  },
	  filters:{
		  text_clear(val,num=4){
			  if(val.length>num){
				  return val.substr(0,num)+"..."
			  }else{
				  return val
			  }
		  }
	  }
	}
</script>

<style scoped lang="less">
	.search{
		padding-top: 46px;
		/deep/ .van-icon-arrow-left{
			color: #000000;
		}
		.jilu{
			position: relative;
			.clear_jilu{
				position: absolute;
				right: 10px;
				font-size: 20px;
			}
		}
	}
	
</style>